package com.fingard.dsp.bank.directbank.abc02;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.fingard.FGBiz;
import com.fingard.client.DspClient;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.directbank.spdb01.SPDB01Header;
import com.fingard.dsp.bank.helpers.FileType;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.ReqAuthForRecDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryRecAuthInfoDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.TcpReceiver;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ABC02AuthorizeForRec extends ABC02Base implements IAuthorizeForRec {
    @Override
    public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) {
        boolean newVersion = getBankConfig().getValueAsBool("AuthNewVersion");
        return newVersion ? d_auth_IBBF39(p_req) : d_auth_IBBF19(p_req);
    }

    public RetAtsAuthForRec d_auth_CFRTD3(ReqAuthForRec p_req) {
        RetAtsAuthForRec tmpRetAts = new RetAtsAuthForRec(p_req.reqHeader);
        try {
            if (p_req.readRecord()) {
                ReqAuthForRecDetail tmpDetail = p_req.readedDetail;
                ABC02Header bankHeader = new ABC02Header();
                bankHeader.CCTransCode = "CFRTD3";
                bankHeader.ReqSeqNo = p_req.reqSeqID;
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("Cmp");
                xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//本方账号
                xmlWriter.writeElementString("DbProv", p_req.reqReserved1);//本方账号省市代码
                xmlWriter.writeElementString("DbCur", convertCurToBank("1"));//本方账号币种
                xmlWriter.writeElementString("DbLogAccNo", "");//本方账簿号
                xmlWriter.writeElementString("CrAccNo", getAbcAccNo(tmpDetail.oppAct));//对方账号
                xmlWriter.writeElementString("CrProv", tmpDetail.reqReserved3);//对方账号省市代码
                xmlWriter.writeElementString("CrCur", convertCurToBank("1"));//对方账号币种
                xmlWriter.writeElementString("TransPwd", "");//密码
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Corp");
                xmlWriter.writeElementString("CrAccName", tmpDetail.oppActName);//对方账号户名
                String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.payType);
                xmlWriter.writeElementString("NVoucherType", NVoucherType);//合约类型
                xmlWriter.writeElementString("ContMob", tmpDetail.reqReserved4);//手机号
                xmlWriter.writeElementString("StartDate", Format.Date8Format.format(new Date()));//合约开始时间
                xmlWriter.writeElementString("SaveTerm", "");// 合约周期
                xmlWriter.writeElementString("TSaveInd", "");// 到期续约标志
                xmlWriter.writeElementString("HighLimit", "");// 扣款金额上限
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Acc");
                xmlWriter.writeElementString("AccType", "");//付款方类型
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                            tmpRetAts.respCode = "0";
                            tmpRetAts.reqSeqID = p_req.reqSeqID;
                            tmpRetAts.retCode = "0";
                        } else {
                            tmpRetAts.respCode = "0";
                            tmpRetAts.reqSeqID = p_req.reqSeqID;
                            tmpRetAts.retCode = "2";
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                tmpRetAts.respInfo = tmpRetRxtInfo;
                            } else {
                                tmpRetAts.respInfo = tmpRetInfo;
                            }
                        }
                    } else {
                        tmpRetAts.respCode = "-1";
                        tmpRetAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpStrRet[1];
                }
            }
        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    public RetAtsAuthForRec d_auth_IBBF19(ReqAuthForRec p_req) {
        RetAtsAuthForRec tmpRetAts = new RetAtsAuthForRec(p_req.reqHeader);
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "IBBF19";
            bankHeader.ReqSeqNo = p_req.reqSeqID;

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeElementString("FileFlag", "1");
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbProv", p_req.ownAct.substring(0, 2));//省市代码
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
            xmlWriter.writeElementString("DbCur", convertCurToBank("1"));//币种代码
            xmlWriter.writeElementString("DbLogAccNo", "");//账簿号
            xmlWriter.writeElementString("SumNum", p_req.totalNum);//签约笔数
            String tmpDataFileName = p_req.reqSeqID + ".txt";
            xmlWriter.writeElementString("BatchFileName", tmpDataFileName);//文件名
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Corp");
            xmlWriter.writeElementString("DbAccName", p_req.ownActName);//委托方户名
            String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.payType);
            xmlWriter.writeElementString("NVoucherType", NVoucherType);
            xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));
            xmlWriter.writeEndElement();
            xmlWriter.writeElementString("Amt", "0");
            xmlWriter.writeEndDocument();
            StringBuilder tmpSbData = new StringBuilder();
            Connection conn = FGBiz.getLocalDbConn();
            while (p_req.readRecord()) {
                tmpSbData.append(p_req.readedDetail.oppAct + "|_|");
                tmpSbData.append("01|_|");
                tmpSbData.append(p_req.readedDetail.oppActName + "|_|");
                tmpSbData.append(p_req.readedDetail.reqReserved4 + "|_|");
                tmpSbData.append(p_req.readedDetail.certNum + "|_|");
                tmpSbData.append("\r\n");
                String uuids = UUID.randomUUID().toString().replaceAll("-", "");
                JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuids, p_req.reqHeader.bankCode, Format.DateTimeFormat.format(new Date()), p_req.reqSeqID + p_req.readedDetail.oppAct, p_req.readedDetail.authCode});
            }
            String tmpFilePath = "";
            if (StringHelper.isNullOrEmpty(bankFront.bkRecFolder)) {
                bankFront.bkRecFolder = bankFront.bkPayFolder;
            }
            tmpFilePath = StringHelper.trimEnd(bankFront.bkRecFolder, File.separator) + File.separator + tmpDataFileName;
            WriteBankLogLn("上传文件地址：" + tmpFilePath);
            StringBuilder smbFileSb = new StringBuilder();
            if (tmpFilePath.startsWith("smb://")) {
                int uploadRet = SmbFileUtil.smbWrite(tmpFilePath, tmpSbData.toString(), getCharset(), smbFileSb);
                if (uploadRet < 0) {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = smbFileSb.toString();
                    tmpRetAts.writeRetToATS();
                    return tmpRetAts;
                }
            } else {
                FileHelper.writeFile(tmpFilePath, tmpSbData);
            }

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    tmpRetAts.respCode = "0";
                    tmpRetAts.reqSeqID = p_req.reqSeqID;
                    tmpRetAts.retCode = tmpRetCode != null && tmpRetCode.equals("0000") ? "2" : "1";
                    if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                        tmpRetAts.retMsg = tmpRetRxtInfo;
                    } else {
                        tmpRetAts.retMsg = tmpRetInfo;
                    }
                    tmpRetAts.respInfo = tmpRetAts.retMsg;
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req.reqSeqID, tmpBkReader.getFirstText("/ap/Cmp/CmeSeqNo")});

                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    public RetAtsAuthForRec d_auth_IBBF39(ReqAuthForRec p_req) {
        RetAtsAuthForRec tmpRetAts = new RetAtsAuthForRec(p_req.reqHeader);
        Connection conn = null;
        try {
            conn = FGBiz.getLocalDbConn();
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "IBBF39";
            bankHeader.ReqSeqNo = p_req.reqSeqID;
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeElementString("FileFlag", "1");
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbProv", getAbcAccProv(p_req.ownAct, p_req.reqReserved1));//省市代码
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
            xmlWriter.writeElementString("DbCur", convertCurToBank("1"));//币种代码
            xmlWriter.writeElementString("DbLogAccNo", "");//账簿号
            xmlWriter.writeElementString("SumNum", p_req.totalNum);//签约笔数
            String tmpDataFileName = p_req.reqSeqID + ".txt";
            xmlWriter.writeElementString("BatchFileName", tmpDataFileName);//文件名
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Corp");
            xmlWriter.writeElementString("DbAccName", p_req.ownActName);//委托方户名
            String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.payType);
            xmlWriter.writeElementString("NVoucherType", NVoucherType);
            xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));
            xmlWriter.writeEndElement();
            xmlWriter.writeElementString("Amt", "0");
            xmlWriter.writeEndDocument();
            StringBuilder tmpSbData = new StringBuilder();
            while (p_req.readRecord()) {
                tmpSbData.append(p_req.readedDetail.oppAct + "|_|");
                tmpSbData.append("01|_|");
                tmpSbData.append(p_req.readedDetail.oppActName + "|_|");
                tmpSbData.append(p_req.readedDetail.reqReserved4 + "|_|");
                tmpSbData.append(p_req.readedDetail.certNum + "|_|");
                if (StringHelper.hasAnyChar(p_req.readedDetail.authItem)) {
                    tmpSbData.append(p_req.readedDetail.authItem + "|_|").append("\r\n");
                } else {
                    String signItem = getBankConfig().getValueAsString("AuthTerm");
                    if (StringHelper.isNullOrEmpty(signItem)) {
                        signItem = "3";
                    }
                    tmpSbData.append(signItem + "|_|").append("\r\n");
                }
                String uuids = UUID.randomUUID().toString().replaceAll("-", "");
                JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuids, p_req.reqHeader.bankCode, Format.DateTimeFormat.format(new Date()), p_req.reqSeqID + p_req.readedDetail.oppAct, p_req.readedDetail.authCode});

            }
            String tmpFilePath = "";
            if (StringHelper.isNullOrEmpty(bankFront.bkRecFolder)) {
                bankFront.bkRecFolder = bankFront.bkPayFolder;
            }
            tmpFilePath = StringHelper.trimEnd(bankFront.bkRecFolder, File.separator) + File.separator + tmpDataFileName;
            WriteBankLogLn("上传文件地址：" + tmpFilePath);
            StringBuilder smbFileSb = new StringBuilder();
            if (tmpFilePath.startsWith("smb://")) {
                int uploadRet = SmbFileUtil.smbWrite(tmpFilePath, tmpSbData.toString(), getCharset(), smbFileSb);
                if (uploadRet < 0) {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = smbFileSb.toString();
                    tmpRetAts.writeRetToATS();
                    return tmpRetAts;
                }
            } else {
                FileHelper.writeFile(tmpFilePath, tmpSbData.toString(), getCharset());
            }
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req.reqHeader.transType, p_req.reqHeader.transType);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetSource = tmpBkReader.getFirstText("/ap/RespSource");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    tmpRetAts.respCode = "0";
                    tmpRetAts.reqSeqID = p_req.reqSeqID;
                    tmpRetAts.retCode = "0000".equals(tmpRetCode) && "0".equals(tmpRetSource) ? "2" : "1";
                    if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                        tmpRetAts.retMsg = tmpRetRxtInfo;
                    } else {
                        tmpRetAts.retMsg = tmpRetInfo;
                    }
                    tmpRetAts.respInfo = tmpRetAts.retMsg;
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req.reqSeqID, tmpBkReader.getFirstText("/ap/Cmp/CmeSeqNo")});

                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    @Override
    public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) throws Exception {
        RetAtsQryAuthForRec retAts = new RetAtsQryAuthForRec(p_req.reqHeader);
        retAts.writeStart();
        Date tmpDateNow = new SimpleDateFormat("yyyyMMdd").parse(p_req.startDate);
        //获取流水号
        String SerialNo = "";
        Connection conn = FGBiz.getLocalDbConn();
        Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req.reqSeqID, p_req.reqHeader.bankCode});
        if (selMap!=null && selMap.size() > 0) {
            SerialNo = selMap.get("BANKREQSEQID").toString();
            WriteBankLogLn("映射核心流水号为：" + SerialNo);
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "根据批次号未找到签约时的流水号";
    //        return retAts;
        }

        //region 业务流水号查询
        //CQRB83
        /*
        ABC02Header bankHeader83 = new ABC02Header();
        bankHeader83.CCTransCode = "CQRB83";
        bankHeader83.ReqSeqNo = Format.DateTime17Format.format(new Date());

        XmlTextWriter xmlWriter83 = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter83, bankHeader83);
        xmlWriter83.writeStartElement("Cmp");
        xmlWriter83.writeElementString("DbProv",  p_req.ownAct.substring(0, 2));//省市代码
        xmlWriter83.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
        xmlWriter83.writeElementString("DbLogAccNo", "");//账簿号
        xmlWriter83.writeElementString("DbCur", "01");//默认人民币币种
        xmlWriter83.writeEndElement();
        xmlWriter83.writeStartElement("Corp");
        xmlWriter83.writeElementString("StartDate",p_req.startDate);
        xmlWriter83.writeElementString("EndDate",p_req.endDate);
        xmlWriter83.writeElementString("NVoucherType","99010007");
        xmlWriter83.writeEndDocument();

        String[] tmpStrRet83 = sendToBank(xmlWriter83.toXmlString());

        this.WriteBankLogLn("83接口银行返回数据为："+tmpStrRet83[1]);
        if (tmpStrRet83[0].length() == 0) {
            {
                StringBuilder tmpSbMsg83 = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader83 = loadBankRespXmlReader(tmpStrRet83[1], tmpSbMsg83);
                if (tmpBkReader83 != null) {
                    String tmpRetCode = tmpBkReader83.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader83.getFirstText("/ap/RespInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        int RecordNum = Integer.parseInt(tmpBkReader83.getFirstText("/ap/Cme/RecordNum"));
                        if(RecordNum>0){

                            int FieldNum = Integer.parseInt(tmpBkReader83.getFirstText("/ap/Cme/FieldNum"));
                            //读取文件
                            String tmpBatchFileName = tmpBkReader83.getFirstText("/ap/Cmp/BatchFileName");
                            String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + tmpBatchFileName;
                            this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                            String tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset());
                            this.WriteBankLogLn("读取的返回文件内容为："+tmpDataMFS);
                            if (tmpDataMFS == null) {
                                this.WriteBankLogLn("读取前置数据文件返回为空，需确认前置文件夹配置和文件是否存在");
                            } else {
                                //获取对应批次的流水号
                                if (tmpDataMFS != null) {
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", FieldNum, RecordNum, tmpSbLog);
                                    if (tmpSbLog.length() == 0) {
                                        //交易日期|流水号|操作员号|总笔数|成功笔数|批次状态
                                        for (int i = 0; i < tmpArrayList.size(); i++) {
                                            //if
                                        }
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "数据为空";
                                }
                            }
                            this.WriteBankLogStep3(tmpDataMFS);
                        }

                    }else{
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetInfo;
                        return retAts;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg83.toString();
                    return retAts;
                }
            }
        }*/
        //endregion

        ABC02Header bankHeader = new ABC02Header();
        bankHeader.CCTransCode = "CQRB85";
        bankHeader.ReqSeqNo = Format.DateTime17Format.format(new Date());

        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("Cmp");
        xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
        xmlWriter.writeElementString("DbProv", p_req.ownAct.substring(0, 2));//省市代码
        xmlWriter.writeElementString("DbCur", "01");//默认人民币币种
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("Cme");
        xmlWriter.writeElementString("SerialNo", SerialNo);

        xmlWriter.writeEndDocument();

        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), p_req.reqHeader.transType, p_req.reqHeader.transType);
        //记录器
        StringBuilder tmpSbLog = new StringBuilder();
        if (tmpStrRet[0].length() == 0) {
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbLog);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                    int RecordNum = StringHelper.changeStrToNum(tmpBkReader.getFirstTextNotNull("/ap/Cme/RecordNum"));
                    if (RecordNum > 0) {
                        int FieldNum = StringHelper.changeStrToNum(tmpBkReader.getFirstTextNotNull("/ap/Cme/FieldNum"));
                        //读取文件
                        String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                        String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + tmpBatchFileName;
                        this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                        String tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset(),tmpSbLog);
                        //获取对应批次的流水号
                        if (tmpSbLog.length() == 0) {
                            String[] str = tmpDataMFS.split("\\n");
                            if (tmpSbLog.length() == 0) {
                                //序号|请求日期|目标方账号|目标方币种|目标方户名数|手机号|身份证号|状态信息|短信发送时间|短信回复时间
                                for (int i = 0; i < str.length; i++) {
                                    RetAtsQryAuthForRecDetail tmpDetail = new RetAtsQryAuthForRecDetail();
                                    String[] repStr = str[i].split("\\|");
                                    String sendTime = "";
                                    if (repStr != null && repStr.length >= 8) {
                                        Map<String, Object> repMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req.reqSeqID + repStr[2], p_req.reqHeader.bankCode});
                                        if (repMap != null && repMap.size() > 0) {
                                            tmpDetail.iSeqno = repMap.get("BANKREQSEQID").toString();
                                            sendTime = repMap.get("TRANSDATE").toString();
                                            WriteBankLogLn("映射明细合同号为：" + tmpDetail.iSeqno + "，发送时间为：" + sendTime);
                                        } else {
                                            WriteBankLogLn("流水号账号：" + p_req.reqSeqID + repStr[2] + "未映射到对应的合同号");
                                        }
                                        tmpDetail.authCode = tmpDetail.iSeqno;
                                        tmpDetail.oppAct = repStr[2].trim();
                                        tmpDetail.oppActName = repStr[4].trim();
                                        tmpDetail.deadLine = Format.Date8Format.format(tmpDateNow);
                                        String tmpResult = "";
                                        String resultInfo = "";
                                        WriteBankLogLn("状态信息为：" + repStr[7]);
                                        if(repStr[7].contains("-")){
                                            tmpResult = repStr[7].split("-")[0];
                                            resultInfo = repStr[7].split("-")[1];
                                        }

                                    /*    if (tmpResult.contains("1") || tmpResult.contains("2") || tmpResult.contains("5") || tmpResult.contains("7") ||
                                                tmpResult.contains("b") || tmpResult.contains("c") || tmpResult.contains("f") || tmpResult.contains("h") || tmpResult.contains("g")) {
                                            tmpDetail.transState = "3";
                                        } else if (tmpResult.contains("e") || tmpResult.contains("4")) {
                                            tmpDetail.transState = "2";
                                        } else {
                                            tmpDetail.transState = "4";
                                        }*/
                                        //超时特殊处理
                                        if(tmpResult.contains("9") && this.getBankConfig().getValueAsBool("useReadTimeForDefinition")){
                                            int hours = this.getBankConfig().getValueAsInt("readTimeHours",0);
                                            if(hours != 0){
                                                if(compareTime(sendTime,hours)){
                                                    //暂定这样处理 改造成映射码形式 c-短信回复超时
                                                    tmpResult = "c";
                                                    resultInfo = "短信回复超时";
                                                }
                                            }
                                        }
                                        tmpDetail.payInfo = resultInfo;
                                        tmpDetail.transState =  p_req.reqHeader.transType + "+" + tmpResult;
                                        tmpDetail.payCode = tmpResult;
                                    } else {
                                        tmpDetail.payInfo = "该条数据银行返回有误";
                                        //未知状态
                                        tmpDetail.transState = "4";
                                    }
                                    retAts.writeRetDetail(tmpDetail);
                                }
                            } else {
                                this.WriteBankLogLn(tmpSbLog.toString());
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpSbLog.toString();
                            }
                        } else {
                            this.WriteBankLogLn(tmpSbLog.toString());
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpSbLog.toString();
                        }
                        this.WriteBankLogStep3(tmpDataMFS);
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetInfo;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpRetInfo;
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpSbLog.toString();
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = tmpStrRet[1];
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
        if (StringHelper.isNullOrEmpty(p_req.oppAct) == false) {
            return d_qry_authInfo_CQRB80(p_req);
        } else {
            return d_qry_authInfo_CQRB79(p_req);
        }
    }

    public RetAtsQryRecAuthInfo d_qry_authInfo_CQRAB8(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "CQRAB8";
            bankHeader.ReqSeqNo = p_req.reqHeader.transSeqID;
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//收款方账号
            xmlWriter.writeElementString("DbAccLogNo", "");//账簿号
            xmlWriter.writeElementString("DbProv", p_req.ownArea);// 收款方省市代码
            xmlWriter.writeElementString("DbCur", convertCurToBank(p_req.ownCur));// 收款方币种
            xmlWriter.writeElementString("CrAccNo", p_req.oppAct);// 付款方账号
            xmlWriter.writeElementString("CrProv", p_req.oppArea);// 付款方省市代码
            xmlWriter.writeElementString("CrCur", convertCurToBank(p_req.oppCur));// 付款方币种
            xmlWriter.writeElementString("ContFlag", "0");
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Corp");
            String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.reqReserve1);
            xmlWriter.writeElementString("NVoucherType", NVoucherType);//合约类型
            xmlWriter.writeElementString("StatCod", "1".equals(p_req.queryTag) ? "1" : "2");//签约状态 1-解约 2-签约 9-全部
            xmlWriter.writeElementString("QryFlag", "0");//查询内容
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Acc");
            xmlWriter.writeElementString("AccType", "1");
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            XmlTextReader tmpBkReader;

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/RecordNum"));
                        int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                        if (tmpRecordNum > 0) {
                            String tmpDataMFS = "";
                            String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                            if (tmpFileFlag != null && tmpFileFlag.equals("1")) {
                                String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                                String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + tmpBatchFileName;
                                this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                                tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset());
                                if (tmpDataMFS == null) {
                                    this.WriteBankLogLn("读取前置数据文件返回完全，需确认前置文件夹配置和文件是否存在");
                                } else {
                                    this.WriteBankLogStep3(tmpDataMFS);
                                }
                            } else {
                                tmpDataMFS = tmpBkReader.getFirstText("/ap/Cmp/RespPrvData1");//
                            }
                            if (tmpDataMFS != null) {
                                StringBuilder tmpSbLog = new StringBuilder();
                                ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum, tmpSbLog);
                                if (tmpSbLog.length() == 0) {
                                    //0-省市代码|1-账号|2-币种|3-户名|4-合约类型|5-签约状态|6-起始日期|7-合约周期|8-查询内容|9-额度
                                    for (int i = 0; i < tmpArrayList.size(); i++) {
                                        RetAtsQryRecAuthInfoDetail tmpDetail = new RetAtsQryRecAuthInfoDetail();
                                        String[] tmpEachArr = tmpArrayList.get(i);
                                        tmpDetail.oppAct = tmpEachArr[1];
                                        tmpDetail.oppActCur = convertCurToATS(tmpEachArr[2]);
                                        tmpDetail.oppActName = tmpEachArr[3];
                                        tmpDetail.queryTag = p_req.queryTag;
                                        tmpDetail.respReserve1 = tmpEachArr[4];
                                        tmpDetail.respReserve2 = tmpEachArr[7];
                                        tmpDetail.respReserve3 = tmpEachArr[9];
                                        tmpRetAts.writeRetDetail(tmpDetail);
                                    }
                                }
                            } else {
                                tmpRetAts.respCode = "-1";
                                tmpRetAts.respInfo = "数据为空";
                            }
                        }
                    } else {
                        tmpRetAts.respCode = "-1";
                        if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                            tmpRetAts.respInfo = tmpRetRxtInfo;
                        } else {
                            tmpRetAts.respInfo = tmpRetInfo;
                        }
                    }
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }

    public RetAtsQryRecAuthInfo d_qry_authInfo_CQRB79(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        tmpRetAts.ownAct = p_req.ownAct;
        try {
            boolean isContinue = true;
            String contFlag = "";
            String contLast = "";
            String tmpRespCode = "";
            String tmpRespInfo = "";
            while (isContinue && tmpRespCode.length() == 0) {
                ABC02Header bankHeader = new ABC02Header();
                bankHeader.CCTransCode = "CQRB79";
                bankHeader.ReqSeqNo = Format.DateTime17Format.format(new Date());

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("Cme");
                xmlWriter.writeElementString("ContLast", contLast);//续查条件
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Cmp");
                xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
                xmlWriter.writeElementString("DbProv", p_req.ownArea);//省市代码
                xmlWriter.writeElementString("DbCur", convertCurToBank(p_req.ownCur));//币种
                xmlWriter.writeElementString("ContFlag", contFlag);//续查标志
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Corp");
                xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));//委托方协议号

                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                            contFlag = tmpBkReader.getFirstText("/ap/Cmp/ContFlag");
                            if ("0".equals(contFlag)) {
                                isContinue = false;
                            }
                            contLast = tmpBkReader.getFirstText("/ap/Cme/ContLast");

                            int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/RecordNum"));
                            int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                            if (tmpRecordNum > 0) {
                                String tmpDataMFS = null;
                                String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                                if (tmpFileFlag != null && tmpFileFlag.equals("1")) {
                                    String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                                    String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + tmpBatchFileName;
                                    this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                                    if ("dspfileserver".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                        WriteBankLogLn("accessBkFileMode：" + bankFront.accessBkFileMode);
                                        DspClient dspClient = new DspClient(bankFront.dspFileServer);
                                        dspClient.charsetName = getCharset();
                                        TcpReceiver tcpRec = dspClient.getFile(FileType.bankFile, tmpFilePath);
                                        if (tcpRec.isCompleted) {
                                            if (tcpRec.isRtnBinaryFile) {
                                                tmpDataMFS = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                            } else {
                                                String errMsg = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                                WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + errMsg);
                                            }
                                        } else {
                                            this.WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + tcpRec.getConnMsg());
                                        }
                                    } else {
                                        tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset());
                                    }
                                    if (tmpDataMFS == null) {
                                        this.WriteBankLogLn("读取前置数据文件返回为null，需确认前置文件夹配置和文件是否存在");
                                    } else {
                                        this.WriteBankLogStep3(tmpDataMFS);
                                    }
                                } else {
                                    tmpDataMFS = tmpBkReader.getFirstText("/ap/Cmp/RespPrvData1");//
                                }
                                if (tmpDataMFS != null) {
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum, tmpSbLog);
                                    if (tmpSbLog.length() == 0) {
                                        for (int i = 0; i < tmpArrayList.size(); i++) {
                                            //0.金融实体代码1|1.合约号1|2.金融实体代码2|3.合约号2|4.子合约号2|5.合约关系类型码|6.关系开始日期|7.委托方协议号|8.目标方账号|9.业务种类|
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            RetAtsQryRecAuthInfoDetail tmpDetail = new RetAtsQryRecAuthInfoDetail();
                                            tmpDetail.oppAct = tmpEachArr[8];
                                            tmpDetail.oppActCur = p_req.oppCur;
                                            tmpDetail.oppActName = "";
                                            //tmpDetail.queryTag = p_req.queryTag;
                                            tmpRetAts.writeRetDetail(tmpDetail);

                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbLog.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "数据为空";
                                }
                            }

                        } else {
                            tmpRespCode = "-1";
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                tmpRespInfo = tmpRetRxtInfo;
                            } else {
                                tmpRespInfo = tmpRetInfo;
                            }
                        }

                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();

                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }
            }

            tmpRetAts.respInfo = tmpRespInfo;
            if ("-1".equals(tmpRespCode)) {
                tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
                tmpRetAts.ownAct = p_req.ownAct;
                tmpRetAts.respCode = tmpRespCode;
                tmpRetAts.respInfo = tmpRespInfo;
            } else {
                tmpRetAts.respCode = "0";
            }

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }

    public RetAtsQryRecAuthInfo d_qry_authInfo_CQRB80(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        tmpRetAts.ownAct = p_req.ownAct;
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.ReqSeqNo = p_req.reqHeader.transSeqID;
            bankHeader.CCTransCode = "CQRB80";

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//委托方账号
            xmlWriter.writeElementString("DbProv", p_req.ownArea);//委托方省市代码
            xmlWriter.writeElementString("DbCur", convertCurToBank(p_req.ownCur));//委托方币种
            xmlWriter.writeElementString("DbLogAccNo", "");//委托方账簿号
            if ("1".equals(p_req.isPrivate)) {
                xmlWriter.writeElementString("CrAccNo", p_req.oppAct);//目标方账号
                xmlWriter.writeElementString("CrProv", "");//目标方省市代码
            } else {
                xmlWriter.writeElementString("CrAccNo", getAbcAccNo(p_req.oppAct));//目标方账号
                if (p_req.oppAct != null && p_req.oppAct.length() > 2) {
                    xmlWriter.writeElementString("CrProv", p_req.oppAct.substring(0, 2));//目标方省市代码
                } else {
                    xmlWriter.writeElementString("CrProv", p_req.oppArea);//目标方省市代码
                }
            }
            xmlWriter.writeElementString("CrCur", convertCurToBank(p_req.oppCur));//目标方币种
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Corp");
            String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.reqReserve1);
            xmlWriter.writeElementString("NVoucherType", NVoucherType);//业务类型
            xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));//委托方协议号
            xmlWriter.writeEndElement();
            xmlWriter.writeElementString("qryflag", p_req.isPrivate);//个人对公标志 1-个人、2-对公
            xmlWriter.writeEndDocument();
            tmpRetAts.ownAct = p_req.ownAct;
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        String tmpConFlag = tmpBkReader.getFirstText("/ap/Cmp/ConFlag");//签约标志 1-已签约、2-未签约
                        tmpRetAts.respCode = "0";
                        if ("1".equals(tmpConFlag)) {
                            RetAtsQryRecAuthInfoDetail tmpDetail = new RetAtsQryRecAuthInfoDetail();
                            tmpDetail.oppAct = p_req.oppAct;
                            tmpDetail.oppActCur = p_req.oppCur;
                            tmpDetail.oppActName = "";
                            tmpDetail.queryTag = p_req.queryTag;
                            tmpRetAts.writeRetDetail(tmpDetail);
                        } else {
                            tmpRetAts.respInfo = "未查询到满足请求条件的签约信息！";
                        }
                    } else {
                        tmpRetAts.respCode = "-1";
                        if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                            tmpRetAts.respInfo = tmpRetRxtInfo;
                        } else {
                            tmpRetAts.respInfo = tmpRetInfo;
                        }
                    }
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }
}
